package com.ruoyi.kubernetes.service.impl;

import com.ruoyi.kubernetes.service.IKubernetesClientNamespaceService;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.NamespaceBuilder;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class KubernetesNamespaceService implements IKubernetesClientNamespaceService {

    @Autowired
    private KubernetesClientService kubernetesClientService;

    @Override
    public List<String> listNamespaces() {
        return kubernetesClientService
                .getKubernetesClient()
                .namespaces()
                .list()
                .getItems()
                .stream()
                .map(Namespace::getMetadata)
                .map(ObjectMeta::getName)
                .collect(Collectors.toList());
    }

    @Override
    public boolean addNamespace(String namespace) {
        try {
            Namespace ns = new NamespaceBuilder().withNewMetadata().withName(namespace).endMetadata().build();
            kubernetesClientService.getKubernetesClient().namespaces().create(ns);
            return true;
        }catch (Exception exception){
            log.error(exception.getMessage());
            return false;
        }
    }

    @Override
    public boolean deleteNamespace(String namespace) {
        return kubernetesClientService.getKubernetesClient().namespaces().withName(namespace).delete();
    }
}
